#include <vector>
#include <algorithm>
using namespace std;
/*
 * @lc app=leetcode.cn id=18 lang=cpp
 *
 * [18] 四数之和
 */

// @lc code=start
class Solution {
public:
    // -2 -1 0 0 1 2
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        vector<vector<int>> res;
        if (nums.size() < 4) return res;
        sort(nums.begin(), nums.end());
        for (int i = 0; i < nums.size() - 3; i++) {
            if (i != 0 && nums[i] == nums[i - 1]) continue;
            for (int j = i + 1; j < nums.size() - 2; j++) {
                if (j != i + 1 && nums[j] == nums[j - 1]) continue;
                int l = j + 1, e = nums.size() - 1;
                while (l < e) {
                    long long x = 0LL + nums[i] + nums[j] + nums[l] + nums[e];
                    if (x == target) {
                        res.push_back({nums[i], nums[j], nums[l], nums[e]});
                        while (l < e && nums[l + 1] == nums[l]) l++;
                        while (l < e && nums[e] == nums[e - 1]) e--;
                        l++; e--;
                    }
                    else if (x < target) {
                        l++;
                    } else e--;
                }
            }
        }
        return res;
    }
};
// @lc code=end

